import { usePermissionStore } from '@/stores/permission'
import { useUserStore } from '@/stores/user'
import type { PermissionInfo } from '@/types/permission.type'
import { getToken, removeToken } from '@/utils/auth'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import { baseRoutes, catchAllRoute } from './baseRoutes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  easing: 'ease',
  speed: 500
})

// 延迟导入 Layout 组件
const Layout = () => import('@/layout/index.vue')

// 组件映射
const componentMap: Record<string, () => Promise<any>> = {
  'system/user/index': () => import('@/views/system/user/index.vue'),
  'system/role/index': () => import('@/views/system/role/index.vue'),
  'system/dept/index': () => import('@/views/system/dept/index.vue'),
  'system/menu/index': () => import('@/views/system/menu/index.vue'),
  'system/permission/index': () => import('@/views/system/permission/index.vue'),
  'system/login-log/index': () => import('@/views/system/login-log/index.vue'),
  'profile/index': () => import('@/views/profile/index.vue'),
  'profile/password': () => import('@/views/profile/password.vue')
}

const router = createRouter({
  history: createWebHistory(),
  routes: baseRoutes
})

// 白名单路由
const whiteList = ['/login']

// 标记是否已添加动态路由
let hasAddRoutes = false

router.beforeEach(async (to, from, next) => {
  // 开始加载进度条
  NProgress.start()
  
  const token = getToken()
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (!userStore.userInfo) {
        try {
          // 获取用户信息
          await userStore.getUserInfo()
          
          // 获取权限树
          await permissionStore.fetchPermissionTree()
          
          // 根据权限树生成路由
          const accessRoutes = generateRoutes(permissionStore.permissionTree)
          
          // 如果有动态路由，则添加
          if (accessRoutes.length > 0) {
            // 将动态路由添加到根路由下
            accessRoutes.forEach(route => {
              router.addRoute('/', route)
            })
            // 添加通配符路由
            router.addRoute(catchAllRoute)
            hasAddRoutes = true
            // 确保路由已添加完成后再跳转
            next({ ...to, replace: true })
          } else {
            // 如果没有动态路由，直接跳转
            // 如果访问的不是基础路由，则重定向到404
            if (!baseRoutes.some(route => route.path === to.path)) {
              next('/404')
            } else {
              next()
            }
          }
        } catch (error) {
          // 获取用户信息失败，只清除本地状态，不调用登出接口
          userStore.token = ''
          userStore.userInfo = null
          removeToken()
          next(`/login?redirect=${to.path}`)
        }
      } else {
        // 如果用户信息已存在但路由未添加，则添加路由
        if (!hasAddRoutes) {
          const accessRoutes = generateRoutes(permissionStore.permissionTree)
          
          if (accessRoutes.length > 0) {
            // 将动态路由添加到根路由下
            accessRoutes.forEach(route => {
              router.addRoute('/', route)
            })
            // 添加通配符路由
            router.addRoute(catchAllRoute)
            hasAddRoutes = true
            next({ ...to, replace: true })
          } else {
            // 如果没有动态路由，直接跳转
            // 如果访问的不是基础路由，则重定向到404
            if (!baseRoutes.some(route => route.path === to.path)) {
              next('/404')
            } else {
              next()
            }
          }
        } else {
          next()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

// 路由加载完成后结束进度条
router.afterEach(() => {
  NProgress.done()
})

// 根据权限树生成路由
const generateRoutes = (permissions: PermissionInfo[] | null | undefined): RouteRecordRaw[] => {
  // 如果权限树为空，返回空数组
  if (!permissions || !Array.isArray(permissions)) {
    return []
  }

  const routes: RouteRecordRaw[] = []
  
  for (const permission of permissions) {
    if (permission.permissionType === 1) { // 菜单类型
      // 获取组件
      let component = null
      if (permission.component === 'Layout') {
        component = Layout
      } else if (permission.component) {
        // 从组件路径中提取组件名称
        const componentName = permission.component.replace(/^\/+/, '').replace(/\.vue$/, '')
        component = componentMap[componentName]
        if (!component) {
          continue
        }
      }

      const route: RouteRecordRaw = {
        path: permission.path || '',
        name: permission.permissionCode,
        component,
        meta: {
          title: permission.permissionName,
          icon: permission.icon
        },
        children: []
      }

      // 如果有子菜单，递归生成子路由
      if (permission.children && permission.children.length > 0) {
        route.children = generateRoutes(permission.children)
      }

      // 如果没有子菜单且没有组件，则跳过
      if (!route.children?.length && !component) {
        continue
      }

      routes.push(route)
    }
  }
  
  return routes
}

export default router 